package com.app.business.web.business;

import com.app.business.calculate.CalculateUtils;
import com.app.business.en.Status;
import com.app.business.model.AdjustArea;
import com.app.business.model.Contract;
import com.app.business.service.AdjustAreaService;
import com.app.business.service.ContractService;
import com.app.business.service.HandInMoneyService;
import com.app.business.service.ZsProjectService;
import com.app.system.jpa.PageBean;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.DateUtils;
import com.app.system.utils.dataType.IntegerUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 面积调换管理
 * Created by ddz on 2019/2/12.
 */
@Controller
@RequestMapping("/business/adjustArea/*")
@SuppressWarnings("all")
public class AdjustAreaController {
    @Autowired
    private ContractService contractService;
    @Autowired
    private AdjustAreaService adjustAreaService;
    @Autowired
    private DataDictService dataDictService;
    @Autowired
    private ZsProjectService zsProjectService;


    /**
     * 面积合并管理列表
     *
     * @param modelMap
     */
    @RequestMapping("list")
    @RequiresPermissions("adjustArea:list")
    public void list() {
    }


    /**
     * 加载面积管理信息数据
     *
     * @return
     */
    @RequestMapping("loadAdjustAreaList")
    @ResponseBody
    @RequiresPermissions("adjustArea:loadAdjustAreaList")
    public Map loadAdjustAreaList() {
        List<Map> listData = Lists.newArrayList();
        PageBean<Contract> contractPageBean = this.contractService.getAdjustAreaContractPageBean();
        List<Contract> contractList = contractPageBean.getDatas();
        Map<String, DataDict> groupMap = this.dataDictService.getMapByParentNameForValue("组别");
        Map<String, DataDict> signMap = this.dataDictService.getMapByParentNameForValue("签约状态");
        Map<String, DataDict> checkMap = this.dataDictService.getMapByParentNameForValue("复核状态");
        if (CollectionUtils.isNotEmpty(contractList)) {
            Map<String, Object> item = null;
            for (Contract contract : contractList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", contract.getId());
                item.put("zsProjectName", StringUtils.getNotNull(contract.getZsProject().getProjectName()));
                item.put("groupCode", StringUtils.dataDictShow(groupMap.get(contract.getGroupCode())));
                item.put("contractCode", StringUtils.getNotNull(contract.getContractCode()));
                item.put("name", StringUtils.getNotNull(contract.getName()));
                item.put("propertyChangeArea", BigDecimalUtils.getNotNullStr(contract.getPropertyChangeArea()));
                item.put("adjustArea", BigDecimalUtils.getNotNullStr(contract.getAdjustArea()));
                item.put("limitHouseAreaTotal", BigDecimalUtils.getNotNullStr(contract.getLimitHouseAreaTotal()));
                item.put("azSignStatus", IntegerUtils.getNotNull(contract.getAzSignStatus()));
                item.put("azSignStatusStr", StringUtils.dataDictShow(signMap.get(IntegerUtils.getNotNull(contract.getAzSignStatus()).toString())));
                item.put("financeCheckStatus", IntegerUtils.getNotNull(contract.getFinanceCheckStatus()));
                item.put("financeCheckStatusStr", StringUtils.dataDictShow(checkMap.get(IntegerUtils.getNotNull(contract.getFinanceCheckStatus()).toString())));
                item.put("azSignDate", contract.getAzSignStatus().equals(Status.NO.getIndex()) ? "" : DateUtils.dateToStringDefault(contract.getAzSignDate()));
                listData.add(item);
            }
        }
        return LayUiUtils.page(contractPageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 面积合并数据修改
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("form")
    @RequiresPermissions("adjustArea:form")
    public void form(HttpServletRequest request, ModelMap modelMap) {
        Map<String, DataDict> groupMap = this.dataDictService.getMapByParentNameForValue("组别");
        int contractId = ParamUtils.getInt(request, "contractId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "数据错误！");
        modelMap.addAttribute("groupMap", groupMap);
        modelMap.addAttribute("contract", contract);
    }

    /**
     * 面积合并移除管理
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("deleteForm")
    public void deleteForm(HttpServletRequest request, ModelMap modelMap) {
        Map<String, DataDict> groupMap = this.dataDictService.getMapByParentNameForValue("组别");
        int contractId = ParamUtils.getInt(request, "contractId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "数据错误！");
        modelMap.addAttribute("groupMap", groupMap);
        modelMap.addAttribute("contract", contract);
    }

    /**
     * form页面根据搜索找到某一户
     *
     * @return
     */
    @RequestMapping("loadAdjustAreaTableDate")
    @ResponseBody
    @RequiresPermissions("adjustArea:loadAdjustAreaTableDate")
    public Map loadAdjustAreaTableDate(HttpServletRequest request) {

        int outContractId = ParamUtils.getInt(request, "outContractId", 0);//转出方id
        Contract outContract = this.contractService.findOne(outContractId);
        Precondition.checkAjaxArguement(outContract != null, "1111", "数据错误！");
        Integer zsProjectId = outContract.getZsProject().getId();
        List<Map> listData = Lists.newArrayList();
        PageBean<Contract> contractPageBean = this.contractService.contractPageBeanByProjectId(outContractId);

        List<Contract> contractList = contractPageBean.getDatas();

        if (CollectionUtils.isNotEmpty(contractList)) {
            Map<String, Object> item = null;
            for (Contract contract : contractList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", contract.getId());
                item.put("zsProjectName", StringUtils.getNotNull(contract.getZsProject().getProjectName()));
                item.put("contractCode", StringUtils.getNotNull(contract.getContractCode()));
                item.put("name", StringUtils.getNotNull(contract.getName()));
                item.put("propertyChangeArea", BigDecimalUtils.getNotNullStr(contract.getPropertyChangeArea()));
                item.put("adjustArea", BigDecimalUtils.getNotNullStr(contract.getAdjustArea()));
                item.put("limitHouseAreaTotal", BigDecimalUtils.getNotNullStr(contract.getLimitHouseAreaTotal()));
                listData.add(item);
            }
        }
        return LayUiUtils.page(contractPageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 加载有合并信息的数据
     * @param request
     * @return
     */
    @RequestMapping("deleteAdjustAreaTableDate")
    @ResponseBody
    public Map deleteAdjustAreaTableDate(HttpServletRequest request) {
        int contractId = ParamUtils.getInt(request, "contractId", 0);//转出方id
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "数据错误！");
        List<Map> listData = Lists.newArrayList();
        PageBean<AdjustArea> adjustAreaPageBean = this.adjustAreaService.adjustAreaPageBeanByContractId(contractId);
        List<AdjustArea> adjustAreaList = adjustAreaPageBean.getDatas();
        if (CollectionUtils.isNotEmpty(adjustAreaList)) {
            Map<String, Object> item = null;
            for (AdjustArea adjustArea : adjustAreaList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", adjustArea.getId());
                item.put("adjustArea", BigDecimalUtils.getNotNullStr(adjustArea.getAdjustArea()));
                item.put("doName", StringUtils.getNotNull(adjustArea.getDoName()));
                item.put("doDate", DateUtils.dateToStringDefault(adjustArea.getDoDate()));
                item.put("memo", StringUtils.getNotNull(adjustArea.getMemo()));
                listData.add(item);
            }
        }
        return LayUiUtils.page(adjustAreaPageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 加载面积管理信息数据
     *
     * @return
     */
    @RequestMapping("loadAdjustAreaRecordForm")
    @ResponseBody
    @RequiresPermissions("adjustArea:loadAdjustAreaRecordForm")
    public Map loadAdjustAreaRecordForm(HttpServletRequest request) {
        List<Map> listData = Lists.newArrayList();
        int contractId = ParamUtils.getInt(request, "contractId", 0);//转出方id
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "数据错误！");
        List<AdjustArea> adjustAreaList = this.adjustAreaService.getAdjustAreaListByContractId(contractId);//转出方调换记录
        if (CollectionUtils.isNotEmpty(adjustAreaList)) {
            Map<String, Object> item = null;
            for (AdjustArea adjustArea : adjustAreaList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", adjustArea.getId());
                item.put("contractCode", StringUtils.getNotNull(contract.getContractCode()));
                item.put("adjustArea", BigDecimalUtils.getNotNullStr(adjustArea.getAdjustArea()));
                item.put("doName", StringUtils.getNotNull(adjustArea.getDoName()));
                item.put("doDate", DateUtils.dateToStringDefault(adjustArea.getDoDate()));
                item.put("memo", StringUtils.getNotNull(adjustArea.getMemo()));
                listData.add(item);
            }
        }
        return LayUiUtils.list(listData);
    }

    /**
     * 面积合并数据修改
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("setAreaForm")
    @RequiresPermissions("adjustArea:setAreaForm")
    public void setAreaForm(HttpServletRequest request, ModelMap modelMap) {
        Map<String, DataDict> groupMap = this.dataDictService.getMapByParentNameForValue("组别");
        int outContractId = ParamUtils.getInt(request, "outContractId", 0);
        int inContractId = ParamUtils.getInt(request, "inContractId", 0);
        Contract outContract = this.contractService.findOne(outContractId);
        Contract inContract = this.contractService.findOne(inContractId);
        Precondition.checkAjaxArguement(outContract != null, "1111", "数据错误！");
        Precondition.checkAjaxArguement(inContract != null, "1111", "数据错误！");
        modelMap.addAttribute("groupMap", groupMap);
        modelMap.addAttribute("outContract", outContract);
        modelMap.addAttribute("inContract", inContract);
    }

    /**
     * 安置项目数据保存
     *
     * @param request
     * @return
     */
    @RequestMapping("setAreaSave")
    @ResponseBody
    @RequiresPermissions("adjustArea:setAreaSave")
    public synchronized Response setAreaSave(HttpServletRequest request) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Response response = this.adjustAreaService.setAreaSave(request);
        return response;
    }

    /**
     * 删除合并信息
     * @param request
     * @return
     */
    @RequestMapping("delAdjustById")
    @ResponseBody
    @Transactional
    public synchronized Response delAdjustById(HttpServletRequest request) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Integer adjustId = ParamUtils.getInt(request, "adjustId", 0);
        AdjustArea adjustArea = this.adjustAreaService.findOne(adjustId);
        Precondition.checkAjaxArguement(adjustArea != null, "1111", "数据错误！");
        //转出Id  转入Id
        List<AdjustArea> adjustAreaList = this.adjustAreaService.getDeleteListByAdjustInfo(adjustArea);
        if (CollectionUtils.isNotEmpty(adjustAreaList)) {
            for (AdjustArea item : adjustAreaList) {
                this.adjustAreaService.delete(item.getId());
                //保存转出方调剂面积
                List<AdjustArea> contractAdjustAreaList = this.adjustAreaService.getAdjustAreaListByContractId(item.getContract().getId());
                BigDecimal newAdjustArea = new BigDecimal("0");
                Contract contract = this.contractService.findOne(item.getContract().getId());
                if (CollectionUtils.isNotEmpty(contractAdjustAreaList)) {
                    for (AdjustArea contractAdjustArea : contractAdjustAreaList) {
                        newAdjustArea = BigDecimalUtils.getSum(newAdjustArea, contractAdjustArea.getAdjustArea());
                    }
                }
                contract.setAdjustArea(newAdjustArea);
                this.contractService.save(contract);
                CalculateUtils.main(contract.getId());//删除结束后重新执行计算
            }
        }
        return new Response("0001", "删除成功");
    }
}
